package com.heatup.apt.api.service.impl;

import com.heatup.apt.api.service.*;
import com.heatup.apt.common.constants.*;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.common.dao.user.*;
import com.heatup.apt.common.exception.OrderNotFoundException;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.model.IndexResource;
import com.heatup.apt.model.api.OrderInfoResultModel;
import com.heatup.apt.model.api.coupon.CouponApiResultModel;
import com.heatup.apt.model.coach.CoachInfo;
import com.heatup.apt.model.course.CourseInfoModel;
import com.heatup.apt.model.user.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by earvin on 2017/7/13.
 */
@Service
public class ProtalServiceImpl implements ProtalService {

    private static final Logger logger = LoggerFactory.getLogger(ProtalServiceImpl.class);

    @Autowired
    private IndexResourceMapper indexResourceMapper;

    @Autowired
    private CourseInfoMapper courseInfoMapper;

    @Autowired
    private CoachInfoMapper coachInfoMapper;

    @Autowired
    private CouponDetailMapper couponDetailMapper;

    @Autowired
    private MyBooksService myBooksService;

    @Autowired
    private OrderInfoResultMapper orderInfoResultMapper;

    @Resource
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserProductServiceService userProductServiceService;

    @Autowired
    private UserMealCouponMapper userMealCouponMapper;
    
    @Autowired
    private DataDictService dataDictService;

    @Override
    public Map<String, Object> protalInfoService(UserInfo userInfo) throws OrderNotFoundException {
        Map<String,Object> respMap = new HashMap<>();
        //1.首页通知
        List<IndexResource> notices =  indexResourceMapper.queryListByMainTypeAndSubType(3,3);
        respMap.put("notices",notices);

        //2.首页banner图
        List<IndexResource> banners = indexResourceMapper.queryListByMainTypeAndSubType(1,1);
        respMap.put("banners",banners);

        //3.自助包月卡 5天内到期提醒标志信息，不是檬会员则提醒立即开通
        //包月卡状态 1，未开通 2，快到期 3，已开通，未到期
        int monthlyCardStatus = 1;
        int dayNum = 0;
        UserProductService userProductService = userProductServiceService.queryUserProductServiceByUserIdAndType(userInfo.getId(), UserProductServiceConstants.SELFTYPESERVICE);
        if(userProductService!=null && userProductService.getIsvalid() == 1){
            try{
                dayNum = DateUtils.daysBetween(new Date(),userProductService.getEndDate());
            }catch (Exception e){
                e.printStackTrace();
                logger.error("首页时间类型转换失败:",e);
            }

            if(dayNum<6){
                monthlyCardStatus = 2;
            }else{
                monthlyCardStatus = 3;
            }
        }
        /** modify by Earvin 2017-11-01
         * 围裙私教是自助年卡判断
        //当前是会员
        if(UserConstants.UserLevel.vip.getIndex()==userInfo.getLevel()){
            try{
                dayNum =  DateUtils.daysBetween(new Date(),userInfo.getVipEndTime());
            }catch (ParseException e){
                e.printStackTrace();
                logger.error("类型转换失败:",e);
            }
            if(dayNum<6){
                monthlyCardStatus = 2;
            }else{
                monthlyCardStatus = 3;
            }
        }*/
        respMap.put("dayNum",dayNum);
        respMap.put("cardStatus",monthlyCardStatus);

        /**
        Integer userMealCouponCount = 0;
        //餐券模块
        UserMealCoupon userMealCoupon =userMealCouponMapper.queryUserMealCouponByUserId(userInfo.getId());
        if(userMealCoupon!=null){
            userMealCouponCount = userMealCoupon.getMealCount();
        }
        respMap.put("userMealCouponCount",userMealCouponCount);
        */
        // 4.新手推荐：直接查询course_info表

        Map<String,Object> seCoupon = null;
        Map<String,Object> peCoupon = null;
        List<Map<String,Object>> recommendCourse = new ArrayList<>();
        List<CourseInfoModel> courseInfoModels = courseInfoMapper.getSecretExperienceAndPhysicalExaminationCourse();
        if(courseInfoModels !=null && courseInfoModels.size()>0){
            Map<String,Object> courseMap = null;
            for(CourseInfoModel courseInfoModel :courseInfoModels){
                courseMap = new HashMap<>();
                courseMap.put("title",courseInfoModel.getTitle());
                courseMap.put("introduce",courseInfoModel.getIntroduce());
                courseMap.put("price",courseInfoModel.getServicePrice().getPrice());
                courseMap.put("url",courseInfoModel.getResources().get(0).getUrl());
                courseMap.put("courseType",courseInfoModel.getCourseType());
                courseMap.put("courseId",courseInfoModel.getId());

                //添加返回 当日订单限额是否已满
                if (courseInfoModel.getCourseType() != null && courseInfoModel.getCourseType().equals("9")) {
                    courseMap.put("isCanOrderLimit", orderInfoMapper.queryPrivateBodyExaminationOrderMaxLimitByToDay());
                }
                if (courseInfoModel.getCourseType() != null && courseInfoModel.getCourseType().equals("10")) {
                    courseMap.put("isCanOrderLimit", orderInfoMapper.queryPrivateExperienceOrderMaxLimitByToDay());
                }

                CouponApiResultModel couponApiResultModel = couponDetailMapper.queryAboutSecretCouponDetail(userInfo.getId(),Integer.valueOf(courseInfoModel.getCourseType()));
                if(couponApiResultModel !=null){
                    //体测券
                    if(OrderContants.OrderType.physical_examination.getType().equals(courseInfoModel.getCourseType())){
                        peCoupon = new HashMap<>();
                        peCoupon.put("couponType",couponApiResultModel.getCoupon_type());
                        peCoupon.put("couponName",couponApiResultModel.getCoupon_name());
                        BigDecimal cashMoney = couponApiResultModel.getCash_money();
                        if(cashMoney !=null){
                            peCoupon.put("cashMoney",cashMoney);
                        }
                    }else if(OrderContants.OrderType.secret_experience.getType().equals(courseInfoModel.getCourseType())){
                        seCoupon = new HashMap<>();
                        seCoupon.put("couponType",couponApiResultModel.getCoupon_type());
                        seCoupon.put("couponName",couponApiResultModel.getCoupon_name());
                        BigDecimal cashMoney = couponApiResultModel.getCash_money();
                        if(cashMoney !=null){
                            seCoupon.put("cashMoney",cashMoney);
                        }
                    }
                }
                recommendCourse.add(courseMap);
            }
        }
        respMap.put("seCoupon",seCoupon);
        respMap.put("peCoupon",peCoupon);
        respMap.put("recommendCourse",recommendCourse);

        //5.团课即将开始
        OrderInfoResultModel model = orderInfoResultMapper.queryUpCommingOrder(userInfo.getId());
        if(model !=null){
           Map<String,Object> upCommingOrder = myBooksService.orderDetail(model.getId(),userInfo.getId());
           respMap.put("upCommingOrder",upCommingOrder);
        }

        // 6.推荐教练，显示教练信息，链接到教练详情
        List<IndexResource> recommendCoachs = indexResourceMapper.queryListByMainTypeAndSubType(3,2);
        if(recommendCoachs!=null && recommendCoachs.size()>0){
            IndexResource recommendCoach = recommendCoachs.get(0);
            respMap.put("recommendCoach",recommendCoach);
            CoachInfo coachInfo = coachInfoMapper.selectById(recommendCoach.getCoachId());
            if(coachInfo!=null){
                respMap.put("recommendCoachInfo",coachInfo);
            }
        }
        
        // 7.预售即将开始
        Date retailBeginTime = dataDictService.getBookRetailBeginTime();
        respMap.put("retailBeginTime", retailBeginTime);
        respMap.put("nowDate", DateUtils.getDateShort(new Date()));
        return respMap;
    }


}
